const express = require('express')
const router = express.Router()
const {retError,retSuccess} = require('../../utils/ret')
const fs = require('fs');
const  {logI}  = require('../../log.js')
const moment = require('moment')
const mqtt = require('mqtt');
const userDb = require('../db/user-db')
const urlencode = require('urlencode');
const path = require("path")
const sendFCM = require('../request/send-fcm');

let client= mqtt.connect('mqtt://127.0.0.1:1883', {
    username: 'server',
    password: 'server',
    clientId: 'server'
});

router
    .post('/',  async (req, res) => {
        let mac;
        logI("C-S", mac, "UPLOAD", `${req.headers['content-disposition']}`, "null");
        if(req.headers['content-type'].startsWith('image/jpg') && req.headers['content-disposition']){
            let info = req.headers['content-disposition'].toString().split(";")
            mac = info[0].split("=")[1];
            if(mac){
                logI("C-S", mac, "UPLOAD", `${req.headers['content-disposition']}`, "null");
                const destDir = moment().format("YYYYMMDD");
                const name = info[1].split("=")[1]+".jpg";
                const imgUrl = "/uploads/"+destDir+"/"+info[1].split("=")[1]+".jpg";
                const nickname = urlencode.decode(info[2].split("=")[1]);
                let data =  Buffer.from('');
                const dest_Dir = path.join(__dirname.replace("router", "public"), "uploads", destDir);
                if(!fs.existsSync(dest_Dir)){
                    fs.mkdirSync(dest_Dir);
                }
                const destPath = path.join(__dirname.replace("router", "public"), "uploads", destDir, name);
                req.on('data', chunk => {
                    data = Buffer.concat([data, chunk]);
                });
                req.on('end', () => {
                    if (data) {
                        fs.writeFile(destPath, data, 'binary', async err => {
                            if (err) {
                                retError("UPLOAD",10001,err,res);
                            } else {
                                if(mac){
                                    const time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    await userDb.insertLogNotice(mac,time,imgUrl,nickname);
                                    let token = await userDb.selectGceToken(mac);
                                    let registrationTokens = [];
                                    for(let i = 0;i<token.length;i++){
                                        registrationTokens.push(token[i].token);
                                    }
                                    const ret = {
                                        "mac":mac,
                                        "imgUrl":imgUrl,
                                        "nickname":nickname
                                    }
                                    await sendFCM.sendFCM(registrationTokens,ret);
                                }
                                retSuczcess("UPLOAD",0,"","",res);
                            }
                        });

                    } else {
                        retError("UPLOAD",10002,"No image data received",res);
                    }
                });
            }else{
                retError("UPLOAD",10001,"invalid params",res);
            }
        }else{
            retError("UPLOAD",10001,"invalid params",res);
        }


    })
module.exports = router